package com.brainardphotography.blog.dao;

import java.util.Date;
import java.util.List;
import java.util.logging.Logger;

import com.brainardphotography.blog.BlogEntry;
import com.brainardphotography.blog.utils.BlogEntryUtil;
import com.brainardphotography.blog.utils.Utils;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;

public class BlogEntryDAO extends BaseDAO {
	private static final Logger log = Logger.getLogger(BlogEntryDAO.class.getName());
	
	public List<BlogEntry> findAll() {
		Objectify ofy = ObjectifyService.begin();

		List<BlogEntry> entries = ofy.query(BlogEntry.class)
				.order("-created")
				.list();

		return entries;
	}

	public BlogEntry get(String entryID) {
		Objectify ofy = ObjectifyService.begin();

		BlogEntry entry = ofy.get(BlogEntry.class, entryID);
		return entry;
	}
	
	/**
	 * Returns the most recent blog entry not skipping the home page.
	 * 
	 * @return null if no entries are found.
	 */
	public BlogEntry getHomePageEntry() {
		Objectify ofy = ObjectifyService.begin();
		
		List<BlogEntry> entries = ofy.query(BlogEntry.class)
				.filter("skipHomePage", false)
				.order("-created")
				.list();
		
		if(entries.size() > 0) {
			return entries.get(0);
		}
		
		return null;
	}

	public void save(BlogEntry entry) {
		// TODO Auto-generated method stub
		Objectify ofy = ObjectifyService.begin();

		if (entry.getId() == null || Utils.isStringBlank(entry.getId())) {
			entry.setId(BlogEntryUtil.createEntryIdFromTitle(entry.getTitle()));
		}

		log.info("Saving BlogEntry: " + entry.toString());
		ofy.put(entry);
	}

	public List<BlogEntry> findByDateRange(Date start, Date end) {
		Objectify ofy = ObjectifyService.begin();

		Query<BlogEntry> entries = ofy.query(BlogEntry.class)
			.filter("created >=", start)
			.filter("created <", end);
		
		System.out.println("Entries Query: " + entries.toString());
		
		return entries.list();
	}
	
	public List<BlogEntry> findByDate(Date date) {
		return findByDateRange(date, Utils.getTomorrow(date));
	}
}
